<?php

namespace app\common\order\logic;

use app\common\BaseLogic;
use app\common\config\logic\CommonPickerLogic;
use app\common\config\logic\DictionaryLogic;
use app\common\config\model\ConfigCompany;
use app\common\order\model\Order;
use app\common\product\logic\StoreCategoryLogic;
use app\common\system\logic\UserLogic;

class OrderLogic extends BaseLogic
{
    // 获取订单简介
    public function getBrief($id) {
        return $id;
    }

    public function getOrder($id, $fields="*") {
        $cacheName = "order:{$id}";

        if ($fields == "*") {
            $data = $this->redis->hGetAll($cacheName);
        } else {
            $data = $this->redis->hMGet($cacheName, $fields);
        }

        if (empty($data['id'])) {
            $model = new Order();
            $row = $model->where('id', $id)->find();
            if (!empty($row)) {
                $data = $row->getData();
                $this->redis->hMSet($cacheName, $data);
            } else {
                $data = [];
            }
        }

        if (empty($data)) return [];
        // 需要格式化的字段
        $data['sign_date'] = date('Y-m-d', $data['sign_date']);
        $data['create_time'] = date('Y-m-d', $data['create_time']);
        $data['files'] = json_decode($data['files'], true);

        // 获取类型
        $categoryLogic = new StoreCategoryLogic();
        $data['category'] = $categoryLogic->getStoreCategory($data['category_id'], ['id', 'title']);

        // 获取公司
        $dictionaryLogic = new DictionaryLogic();
        $data['company'] = $dictionaryLogic->getItem($data['company_id'], ConfigCompany::class, ['id', 'title']);

        // 获取合作模式
        $commonPickerLogic = new CommonPickerLogic();
        $data['cooperation'] = $commonPickerLogic->getPickerItem('cooperation', $data['cooperation_id']);

        $userLogic = new UserLogic();
        $data['user'] = $userLogic->getUser($data['user_id'], ['id', 'realname', 'avatar', 'status']);
        return $data;
    }

    public function resetCache($id){
        $cacheName = "order:{$id}";
        $this->redis->del($cacheName);
        $this->getOrder($id);
    }
}